import os
import sys
import logging
import configparser
import pygame
from PyQt5.QtWidgets import (QApplication, QDialog, QFormLayout, QLineEdit, QPushButton, QHBoxLayout, QMessageBox, QLabel)
from PyQt5.QtCore import Qt
from database import DatabaseManager
from export_manager import ExportManager

# 配置日志系统
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('app.log', encoding='utf-8'),
        logging.StreamHandler(sys.stdout)
    ]
)
logger = logging.getLogger('ticket_system')

class AppInitializer:
    def __init__(self):
        self.base_dir = os.path.dirname(os.path.abspath(__file__))
        self.config = None
        self.db_manager = None
        self.export_manager = None
        self.sounds = {}

    def load_config(self):
        """加载应用配置文件"""
        config_path = os.path.join(self.base_dir, 'config.ini')
        self.config = configparser.ConfigParser()
        self.config.read(config_path, encoding='utf-8')
        logger.info("配置文件加载成功")
        return self.config

    def show_config_dialog(self):
        """显示数据库配置对话框"""
        dialog = QDialog()
        dialog.setWindowTitle('数据库配置 - 初始化')
        dialog.setFixedSize(400, 300)
        layout = QFormLayout(dialog)
        layout.setSpacing(15)
        layout.setContentsMargins(30, 30, 30, 20)

        # 添加标题
        title_label = QLabel('请配置数据库连接信息')
        title_label.setStyleSheet('font-size: 18px; font-weight: bold; color: #333;')
        title_label.setAlignment(Qt.AlignCenter)
        layout.addRow(title_label)

        # 创建输入框
        host_input = QLineEdit()
        host_input.setPlaceholderText('例如: localhost 或 192.168.1.100')
        host_input.setStyleSheet('font-size: 14px;')
        user_input = QLineEdit()
        user_input.setPlaceholderText('数据库登录用户名')
        user_input.setStyleSheet('font-size: 14px;')
        password_input = QLineEdit()
        password_input.setEchoMode(QLineEdit.Password)
        password_input.setPlaceholderText('数据库登录密码')
        password_input.setStyleSheet('font-size: 14px;')
        db_input = QLineEdit()
        db_input.setPlaceholderText('数据库名称')
        db_input.setStyleSheet('font-size: 14px;')
        aes_key_input = QLineEdit()
        aes_key_input.setEchoMode(QLineEdit.Password)
        aes_key_input.setPlaceholderText('数据加密AES密钥')
        aes_key_input.setStyleSheet('font-size: 14px;')

        # 添加到布局
        layout.addRow('数据库IP:', host_input)
        layout.addRow('用户名:', user_input)
        layout.addRow('密码:', password_input)
        layout.addRow('数据库名:', db_input)
        layout.addRow('AES密钥:', aes_key_input)

        # 添加按钮
        btn_layout = QHBoxLayout()
        save_btn = QPushButton('保存配置')
        #save_btn.setStyleSheet('background-color: #4CAF50; color: white; padding: 12px 24px; border: none; border-radius: 4px; font-size: 16px; font-weight: bold;')
        cancel_btn = QPushButton('取消')
        #cancel_btn.setStyleSheet('background-color: #f44336; color: white; padding: 12px 24px; border: none; border-radius: 4px; font-size: 16px; font-weight: bold;')
        btn_layout.addWidget(save_btn)
        btn_layout.addWidget(cancel_btn)
        layout.addRow(btn_layout)

        # 连接信号
        save_btn.clicked.connect(dialog.accept)
        cancel_btn.clicked.connect(dialog.reject)

        # 显示对话框
        if dialog.exec_() == QDialog.Accepted:
            # 验证输入
            if not all([host_input.text(), user_input.text(), db_input.text(), aes_key_input.text()]):
                QMessageBox.critical(dialog, '错误', '请填写所有必填字段（IP、用户名、数据库名、AES密钥）')
                return self.show_config_dialog()  # 重新显示对话框

            # 保存配置
            config_path = os.path.join(self.base_dir, 'config.ini')
            self.config = configparser.ConfigParser()
            self.config['Database'] = {
                'host': host_input.text(),
                'user': user_input.text(),
                'password': password_input.text(),
                'database': db_input.text(),
                'aes_key': aes_key_input.text()
            }
            with open(config_path, 'w', encoding='utf-8') as f:
                self.config.write(f)
            logger.info('配置文件创建成功')
            return True
        return False

    def show_warning_dialog(self):
        """显示配置修改警告对话框"""
        msg_box = QMessageBox()
        msg_box.setWindowTitle('警告 - 配置已存在')
        msg_box.setIcon(QMessageBox.Warning)
        msg_box.setText('检测到已存在配置文件！')
        msg_box.setInformativeText('修改数据库配置可能导致数据连接失败或数据丢失。\n是否继续修改配置？')
        msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
        msg_box.setDefaultButton(QMessageBox.No)
        msg_box.setStyleSheet('''
            QMessageBox {font-size: 14px;}
            QPushButton {min-width: 80px; padding: 5px;}
        ''')

        return msg_box.exec_() == QMessageBox.Yes

    def init_database(self):
        """初始化数据库连接"""
        if not self.config:
            self.load_config()

        self.db_manager = DatabaseManager(self.config)
        logger.info("数据库连接初始化成功")
        return self.db_manager

    def init_export_manager(self):
        """初始化导出管理器"""
        if not self.db_manager:
            self.init_database()

        self.export_manager = ExportManager(self.db_manager)
        logger.info("导出管理器初始化成功")
        return self.export_manager

    def init_sound_effects(self):
        """初始化音效系统"""
        try:
            pygame.mixer.init()
            sound_dir = os.path.join(self.base_dir, 'sound')
            sound_files = {
                'success': '1.wav',
                'repeat': '2.wav',
                'failure': '3.wav'
            }

            for sound_name, filename in sound_files.items():
                sound_path = os.path.join(sound_dir, filename)
                if os.path.exists(sound_path):
                    self.sounds[sound_name] = pygame.mixer.Sound(sound_path)
                    logger.info(f"加载音效成功: {sound_name}")
                else:
                    logger.warning(f"音效文件不存在: {sound_path}")
                    self.sounds[sound_name] = None

            return self.sounds
        except Exception as e:
            logger.error(f"音效系统初始化失败: {str(e)}")
            return {}

    def initialize_all(self):
        """执行所有初始化操作，包含图形界面引导"""
        try:
            config_path = os.path.join(self.base_dir, 'config.ini')
            config_exists = os.path.exists(config_path)

            # 配置文件处理逻辑
            if not config_exists:
                # 首次运行 - 显示配置对话框
                if not self.show_config_dialog():
                    logger.error("用户取消配置，初始化终止")
                    return False
            else:
                # 配置已存在 - 显示警告
                if self.show_warning_dialog():
                    # 用户确认修改
                    if not self.show_config_dialog():
                        logger.error("用户取消配置修改")
                        return False
                else:
                    # 加载现有配置
                    self.load_config()

            # 继续其他初始化步骤
            self.init_database()
            # 初始化数据库表结构
            self.db_manager.init_database()
            self.init_export_manager()
            self.init_sound_effects()
            logger.info("应用程序初始化完成")
            return True
        except Exception as e:
            logger.error(f"初始化失败: {str(e)}", exc_info=True)
            QMessageBox.critical(None, '初始化失败', f'应用程序初始化出错:\n{str(e)}')
            return False

# 创建初始化实例供外部使用
initializer = AppInitializer()

if __name__ == '__main__':
    # 创建Qt应用实例
    app = QApplication(sys.argv)
    # 确保中文显示正常
    font = app.font()
    font.setFamily('SimHei')
    app.setFont(font)
    
    # 执行初始化
    initializer = AppInitializer()
    success = initializer.initialize_all()
    sys.exit(0 if success else 1)